package models

import (
	"fmt"
	"source-admin-go/pkg/e"
	"source-admin-go/src/config/DataBases"
	"time"
)

const (
	NotDelete = 1
	DELETED   = 0
)

type IdModel struct {
	ID uint `json:"id" gorm:"comment:1:主键，自增ID"`
}

// 基础表
type BaseModel struct {
	CTime time.Time `json:"c_time" gorm:"type:timestamp;default:CURRENT_TIMESTAMP;comment:创建时间"`
	UTime time.Time `json:"u_time" gorm:"type:timestamp;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;comment:1:更新时间"`
	DTime time.Time `json:"d_time" gorm:"type:timestamp;default:'2021-01-01 00:00:00';comment:删除时间"`
	IsDel bool      `json:"is_del" gorm:"default:1;comment:1:存在、0:已删除"`
}

func (b BaseModel) InitTable() {
	db := DataBases.DB
	err := db.AutoMigrate(&UserModel{}, &TokenModel{})
	if err != nil {
		e.ErrorLogPrintln(fmt.Sprintf("Database migration failed:【%v】", err))
	}
}

// 获取第一条数据
func (BaseModel) GetFirst(data interface{}) {
	DataBases.DB.First(data)
}

// 获取最后一条数据
func (b BaseModel) GetLast(data interface{}) {
	DataBases.DB.Last(data)
}

// 根据ID查询数据
func (b BaseModel) GetDataById(id uint, data interface{}) {
	DataBases.DB.First(data, id)
}

// 获取所有未删除数据 GetAllNotDel(&data)
func (b BaseModel) GetAllNotDel(data interface{}) {
	DataBases.DB.Where("is_del = ?", NotDelete).Find(data)
}

// 获取所有已删除数据
func (b BaseModel) GetAllDeleted(data []interface{}) {
	DataBases.DB.Where("is_del = ?", DELETED).Find(&data)
}

// 添加数据，返回插入数据的ID
func (b BaseModel) AddData(data interface{}) {
	DataBases.DB.Create(data)
}

// 批量添加数据，返回插入的数据ID集合
func (b BaseModel) AddDataList(data []interface{}) {
	for _, item := range data {
		b.AddData(item)
	}
}

// 根据ID软删除一条数据
func (b BaseModel) DeleteDataById(data interface{}) int64 {
	affected := DataBases.
		DB.
		Model(data).
		Where("is_del <> ?", DELETED).
		Updates(map[string]interface{}{"is_del": DELETED, "d_time": time.Now()}).
		RowsAffected
	return affected
}

// 根据ID批量软删除一条数据
func (b BaseModel) DeleteDataByIds(data []*interface{}) int64 {
	var deleteCount = int64(0)
	for _, item := range data {
		deleteCount += b.DeleteDataById(item)
	}
	return deleteCount
}

// 通过ID更新数据表字段
func (b BaseModel) UpdateDataById(data interface{}) int64 {
	return DataBases.
		DB.
		Model(data).
		Omit("d_time", "u_time", "c_time", "is_del", "id").
		Save(data).
		RowsAffected
}

// 批量更新
func (b BaseModel) UpdateUsersById(data []interface{}) int64 {
	var count = int64(0)
	for _, item := range data {
		count += b.UpdateDataById(item)
	}
	return count
}
